#!/usr/bin/python
"""
################################################################################
返回一个目录中和其下的所有匹配得上文件名正则图样的文件；

自定义了标准库中现在已弃用的查找模块：例如 import as "PP4E.Tools.find"；
使用了 os.walk循环，不支持裁剪子目录，可作为顶级脚本运行。

find()是一个生成器，它是用os.walk()生成器来产出匹配上的文件名；
使用findlist()来强迫find()生成器生成列表。




Return all files matching a filename pattern at and below a root directory;

custom version of the now deprecated find module in the standard library:
import as "PP4E.Tools.find"; like original, but uses os.walk loop, has no 
support for pruning subdirs, and is runnable as a top-level script; 

find() is a generator that uses the os.walk() generator to yield just
matching filenames: use findlist() to force results list generation;
################################################################################
"""

import fnmatch, os


def find(pattern, startdir=os.curdir):
    for (thisDir, subsHere, filesHere) in os.walk(startdir):        # os.walk会返回一个三元组
        for name in subsHere + filesHere:
            if fnmatch.fnmatch(name, pattern):
                fullpath = os.path.join(thisDir, name)
                yield fullpath


def findlist(pattern, startdir: "起始 搜索目录" = os.curdir, dosort: "是否按 正序排序？" = False):
    matches = list(find(pattern, startdir))
    if dosort: matches.sort()
    return matches


if __name__ == '__main__':
    import sys
    namepattern, startdir = sys.argv[1], sys.argv[2]
    for name in find(namepattern, startdir): print(name)
